﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElectronicsMarket.EMServices;
using ElectronicsMarket.Models;

namespace ElectronicsMarket.Controllers
{
    public class ProductController : Controller
    {
        private const string IMAGE_TYPE = "image/jpeg";
        public int PageSize = 4;
        private ServicesReleaseSoapClient serviceRelease;

        public ProductController()
        {
            serviceRelease = new ServicesReleaseSoapClient();
        }

        public ViewResult List(int category, int page = 1)
        {
            List<Product> prodList = new List<Product>();
            if (category == 0)
            {
                foreach (var item in serviceRelease.getProductList().ToList())
                {
                    Product product = new Product();
                    product.Prod = item;
                    product.Quantity = serviceRelease.getQuantityOfProduct(item.PRODUCT_ID);
                    prodList.Add(product);
                }
            }
            else
            {
                foreach (var item in serviceRelease.getProductList().Where(p => p.PRODUCT_CATEGORY_ID == category).ToList())
                {
                    Product product = new Product();
                    product.Prod = item;
                    product.Quantity = serviceRelease.getQuantityOfProduct(item.PRODUCT_ID);
                    prodList.Add(product);
                }
            }
           
            ProductList productList = new ProductList();
            productList.ProdList = prodList.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            productList.CategoryId = category;
            Page pageInfo = new Page();
            pageInfo.CurrentPage = page;
            pageInfo.TotalItems = prodList.Count;
            pageInfo.ItemsPerPage = PageSize;
            productList.PageInfo = pageInfo;
            return View(productList);
        }

        public FileContentResult GetImage(long productId)
        {
            PRODUCT product = serviceRelease.getProductById(productId);
            if (product != null && product.PRODUCT_IMAGE != null)
            {
                return File(product.PRODUCT_IMAGE, IMAGE_TYPE);
            }
            return null;
        }

        public ViewResult Detail(long prodId)
        {
            PRODUCT product = serviceRelease.getProductById(prodId);
            int quantity = serviceRelease.getQuantityOfProduct(prodId);
            Product prod = new Product();
            prod.Prod = product;
            prod.Quantity = quantity;
            return View(prod);
        }
    }
}